<?php
/**
 * Created by PhpStorm.
 * User: zhongbaitong
 * Date: 2019/9/29
 * Time: 15:54
 */

namespace app\forum\model;

use think\model\concern\SoftDelete;

/**
 * @method belongsTo(string $string)
 * @method hasMany(string $string, string $string1)
 */
class PostComment extends ForumBase
{
    use SoftDelete;

    /**
     * 一对一获取用户信息
     * @return mixed
     */
    public function user()
    {
        return $this->belongsTo("user");
    }

    // 评论点赞
    public function likes(){
        return $this->hasMany("PostLike","comment_id");
    }

    // 评论回复
    public function replys(){
        return $this->hasMany("PostReply","comment_id");
    }

    // 评论的帖子
    public function post(){
        return $this->belongsTo("Post","post_id");
    }

    // 点赞数
    public function getLikesCountAttr($value, $data)
    {
        return $data["extra_like_count"] + $value;
    }

    // 获取留言列表
    public static function getComments($params){

        $post_id = $params["post_id"];

        // 评论只展示最新 3 条
        $replys = function ($q) use($params){
            $q->with(["from_user","to_user"])
                ->withCount(["likes"])
                ->order("create_time desc")
                ->limit($params["reply_nums"] ?? 3);
        };

        $result = self::with(["user","replys"=>$replys])
            ->withCount(["replys","likes"])
            ->orderRaw("likes_count + extra_like_count desc, create_time desc")
            ->lists($params)
            ->where(compact('post_id'))
            ->withAttr('is_like',function ($q,$data) use ($params){
                return PostLike::isliked($data["id"]
                    ,$params["user_id"],2);
            })
            ->withAttr('replys.is_like',function ($q,$data) use ($params){
                return PostLike::isliked($data["id"]
                    ,$params["user_id"],3);
            })
            ->all(["status"=>1])
            ->append(['is_like','replys.is_like']);

        return $result;
    }
}